package transactions;

import dinamica.*;

/**
 * Reusable class to insert array of values into DB.<br>
 * <br><br>
 * Creation date: 5/03/2004<br>
 * Last Update: 5/03/2004<br>
 * (c) 2004 Martin Cordova<br>
 * This code is released under the LGPL license<br>
 * @author Martin Cordova (dinamica@martincordova.com)
 * */
public class InsertDetail extends dinamica.GenericTransaction
{

	/**
	 * Insert array in DB
	 * @param sql SQL template for the INSERT statement, may vary according to 
	 * the context (a new user or an existing user).
	 * @param colName parameter name for the array of values
	 * @throws Throwable
	 */
	public void save(String sql, String colNames) throws Throwable
	{
		
		//get db channel
		Db db = getDb();

		String[] colNameA = colNames.split(",");   //单语句体中,多个字段,用逗号(,)分隔  "xxx1,yyy1"

		//create recordset to hold array
		Recordset detail = new Recordset();

		for (int i=0;i<colNameA.length;i++)
		{
            detail.append(colNameA[i], java.sql.Types.VARCHAR);
		}

		if(getRequest().getParameterValues(colNameA[0])!=null){/*先判断值是否存在*/
		    //System.out.println("字段:"+colNameA[0]);
		    //System.out.println("长度:"+getRequest().getParameterValues(colNameA[0]).length);
            int recordCount = getRequest().getParameterValues(colNameA[0]).length;
            //System.out.println("recordCount"+recordCount);
            for(int i=0;i<recordCount;i++){
    			//add to recordset
    			detail.addNew();
    			for (int j=0;j<colNameA.length;j++){
    			    String colValue[] = getRequest().getParameterValues(colNameA[j]);
    
            		if (colValue == null)   //传空值
            		    detail.setValue(colNameA[j], null);
            		else if(colValue[i] != null && colValue[i] != "")
        				detail.setValue(colNameA[j], new String(colValue[i]));
        			else
        				detail.setValue(colNameA[j], null);
        			
    			}
    			//generate sql
    			String cmd = getSQL(sql, detail);
    			//System.out.println(cmd);
    			//add to batch 
    			db.addBatchCommand(cmd);
            }
    		//insert all records in batch
    		db.exec();
    
    	}
	}

}
